package com.atzly.community.controller.advice;

import com.atzly.community.utils.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zlysimida
 * @date 2021/8/30 - 7:55
 */
@ControllerAdvice(annotations = {Controller.class})
@Slf4j
public class ExceptionAdvice {

    // 处理全部的异常通知
    @ExceptionHandler({Exception.class})
    public void exceptionHandler(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException {
        log.error("服务器发生异常{}",e.getMessage());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            log.error(stackTraceElement.toString());
        }
        // 处理普通请求还是异步请求?
        // 通过请求头做处理
        String xRequestWith = request.getHeader("x-requested-with");
        if("XMLHttpRequest".equals(xRequestWith)){
            // 异步请求返回普通字符串
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtils.JsontoString(1,"服务器处理ajax请求异常!"));
        } else {
            // 非异步异常请求
            response.sendRedirect(request.getContextPath()+"/error");
        }
    }
}
